package javaapplication1.service.serviceImpl;

import java.util.Date;
import java.util.List;

import javaapplication1.dao.AccountDao;
import javaapplication1.dao.PetDao;
import javaapplication1.dao.PetOwnerDao;
import javaapplication1.dao.PetStoreDao;
import javaapplication1.dao.oracleImpl.AccountDaoOracleImpl;
import javaapplication1.dao.oracleImpl.PetDaoOracleImpl;
import javaapplication1.dao.oracleImpl.PetOwnerDaoOracleImpl;
import javaapplication1.dao.oracleImpl.PetStoreDaoOracleImpl;
import javaapplication1.model.Account;
import javaapplication1.model.Pet;
import javaapplication1.model.PetOwner;
import javaapplication1.model.PetStore;
import javaapplication1.service.PetStoreService;
import javaapplication1.view.SessionScope;

public class PetStoreServiceImpl implements PetStoreService {

	private PetDao petDao = new PetDaoOracleImpl();
	private PetOwnerDao petOwnerDao = new PetOwnerDaoOracleImpl();
	private PetStoreDao petStoreDao = new PetStoreDaoOracleImpl();
	private AccountDao accountDao = new AccountDaoOracleImpl();

	@Override
	public void buy(Pet pet) {
		Account account = new Account(0, 2, pet.getId(), pet.getOwnerId(),
				SessionScope.getId(), pet.getPrice(), new Date());
		accountDao.createAccount(account);
		petDao.updatePet(pet.getId(), 0, SessionScope.getId());

		petStoreDao.updatePetStore(SessionScope.getId(),
				SessionScope.getBalance() - pet.getPrice());
		SessionScope.setBalance(SessionScope.getBalance() - pet.getPrice());

		PetOwner petOwner = petOwnerDao.retrievePetOwner(pet.getOwnerId());
		petOwnerDao.updatePetOwner(petOwner.getId(),
				petOwner.getMoney() + pet.getPrice());
	}

	@Override
	public void sell(Pet pet, int ownerId) {
		Account account = new Account(0, 1, pet.getId(), SessionScope.getId(),
				ownerId, pet.getPrice(), new Date());
		accountDao.createAccount(account);
		petDao.updatePet(pet.getId(), ownerId, 0);

		petStoreDao.updatePetStore(SessionScope.getId(),
				SessionScope.getBalance() + pet.getPrice());

		PetOwner petOwner = petOwnerDao.retrievePetOwner(ownerId);
		petOwnerDao.updatePetOwner(petOwner.getId(),
				petOwner.getMoney() - pet.getPrice());
	}

	@Override
	public PetStore login(String username, String password) {
		PetStore loginPetstore = null;
		List<PetStore> petStoreList = this.petStoreDao.retrievePetStoreAll();
		for (PetStore petStore : petStoreList) {
			if (username.equals(petStore.getName())
					&& password.equals(petStore.getPassword())) {
				loginPetstore = petStore;
				SessionScope.setId(loginPetstore.getId());
				SessionScope.setRole(1);
				SessionScope.setUsername(loginPetstore.getName());
				SessionScope.setPassword(loginPetstore.getPassword());
				SessionScope.setBalance(loginPetstore.getBalance());
			}
		}
		return loginPetstore;
	}

}